import {login, getInfo} from '@/api/user.js'
import {removeToken, setRouterId} from "@/utils/storage";
import moment from "moment";
// v-permission='['admin','teacher']'
const state = {
  token: '',
  name: '',
  avator: '',
  user_id: '',
  router_id: '',
  time: ''
};

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token;
  },
  SET_NAME: (state, name) => {
    state.name = name;
  },
  SET_ROUTER_ID: (state, router_id) => {
    state.router_id = router_id;
  },

  SET_AVATOR: (state, avator) => {
    state.avator = avator;
  },
  SET_TIME(state, time) {
    state.time = time;
  }
};

const actions = {
  login({commit}, payload) {
    return new Promise((resolve, reject) => {
      // 请求后台的数据
      login(payload).then(res => {
        let {token, name, router_id, avator} = res;
        commit('SET_TOKEN', token);
        commit('SET_NAME', name);
        commit('SET_ROUTER_ID', router_id);
        commit('SET_TIME', moment(new Date()).format('YYYY-MM-dd hh:mm'));
        resolve(res);
      })
    })
  },
  getInfo({commit, state}) {
    return new Promise((resolve, reject) => {
      getInfo(state.name || 'viewer').then(res => {
        let {router_id} = res;
        commit('SET_ROUTER_ID', router_id);
        setRouterId(router_id);
        resolve(res);
      }).catch(err => {
        reject(err)
      })
    })
  },
  resetToken({commit, state}) {
    return new Promise((resolve, reject) => {
      removeToken();
      resolve();
    })
  },
};

export default {
  state, mutations, actions, namespaced: true
}
